<template>
  <upload-excel :on-success="handleSuccess" :before-upload="beforeUpload" />
</template>

<script>
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'Import',
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    async   handleSuccess({ header, results }) {
      try {
        console.log('从当前excel文件中读出的内容是', results)
        console.log('从当前excel文件 头部', header)
        // results [{姓名:xxx}] 变为  results  [{ username:xxx}] 转英文
        const arr = this.transExcelHander(results)
        console.log('转换之后的格式是', arr)
        // 调用上传的接口，
        const rs = await importEmployee(arr)
        console.log('调用上传的接口', rs)
        // 上传成功之后，回去刚才的页面
        this.$router.back()
        this.$message.success('操作成功')
      } catch (err) {
        this.$message.error(err.message)
      }
    },
    transExcelHander(results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'

      }
      return results.map(item => {
        const rs = {}
        Object.keys(item).forEach(key => {
          const enkey = userRelations[key]
          if (enkey === 'timeOfEntry' || enkey === 'correctionTime') {
            rs[enkey] = new Date(formatExcelDate(item[key]))
          } else {
            rs[enkey] = item[key]
          }
        })
        return rs
      })
    }
  }
}
</script>
<style scoped>
</style>
